﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using TradeMeSDK;

namespace TradeMo
{
    /// <summary>
    /// All information that is stored wether a TM user is loggon or not
    /// </summary>
    public class RecentViewModel : BaseViewModel
    {
        private ObservableCollection<SearchResultItem> _recentlyViewed;
        public ObservableCollection<SearchResultItem> RecentlyViewed
        {
            get { return _recentlyViewed ?? (_recentlyViewed = new ObservableCollection<SearchResultItem>()); }
        }


        public void AddRecentlyViewed(ListedItemDetail listing)
        {
            var current = RecentlyViewed.FirstOrDefault(item => item.Listing.ListingId == listing.ListingId);
            if (current != null)
                RecentlyViewed.Remove(current);
            if (RecentlyViewed.Count > 9)
                RecentlyViewed.RemoveAt(0);
            RecentlyViewed.Insert(0,SearchResultItem.Build(listing));
        }

        private ObservableCollection<SearchCriteria> _recentSearches;
        public ObservableCollection<SearchCriteria> RecentSearches
        {
            get { return _recentSearches ?? (_recentSearches = new ObservableCollection<SearchCriteria>()); }
        }

        public void AddRecentSearch<T>(T searchCriteria) where T : SearchCriteria
        {
			if (searchCriteria == null) return;
			if (string.IsNullOrEmpty(searchCriteria.SearchString)) return;

            var current = RecentSearches.FirstOrDefault(s => s.SearchString == searchCriteria.SearchString);
            if (current != null)
                RecentSearches.Remove(current);
            if (RecentSearches.Count > 9)
                RecentSearches.RemoveAt(9);

            RecentSearches.Insert(0, searchCriteria.Clone());
        }

        public void Clear()
        {
            RecentlyViewed.Clear();
            RecentSearches.Clear();
        }
    }
}
